package com.coderxq.blog.web.contoller;
import com.coderxq.blog.web.dao.OrderMapper;
import com.coderxq.blog.web.dao.UserMapper;
import com.coderxq.blog.web.entity.dto.InsertUsersParam;
import com.coderxq.blog.web.entity.pojo.Order;
import com.coderxq.blog.web.entity.pojo.User;
import com.coderxq.blog.web.entity.vo.UserInfo;
import com.coderxq.blog.utils.CreateImg;
import com.coderxq.blog.utils.ScheduledTaskControl;
import com.coderxq.blog.utils.excel.ExcelUtil;
import com.coderxq.blog.annotation.RequestAnnotation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @Author:     lijingming
 * @Date:       2024/12/9
 * @Description:
 **/
@RestController
@RequestAnnotation
@CrossOrigin
@RequestMapping("/Test")
public class TestApi {
    private final static Logger log = LoggerFactory.getLogger(TestApi.class);


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ScheduledTaskControl scheduledTaskControl;

    @GetMapping("/getImg")
    public String getImg() throws IOException {
        Map list = new HashMap();
        for (int i = 0; i < 8; i++) {
            list.put("加减分" + i, "2");
            list.put("工作态度" + i, "1");
            list.put("绩效系数" + i, "3");
        }
        String path = "d:/upload";
        File newFileDir = new File(path);
        //如果不存在 则创建
        if (!newFileDir.exists()) {
            newFileDir.mkdirs();
        }
        String ImgDownLoadPath = path + "/" + CreateImg.genRandomImageName()+".png";
        try {
            CreateImg.graphicsGeneration(ImgDownLoadPath, list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("完成");
        return ImgDownLoadPath;
    }


    @PostMapping("/insertUser")
    public int insertUser(@RequestBody User user) {

        int result = userMapper.insertUser(user);
        return result;
    }

    @PostMapping("/insertUsers")
    public int insertUsers(@RequestBody InsertUsersParam usersParam) {
        List<User> users = usersParam.getUsers();
        for(User user : users){

        }

        int result = userMapper.insertUsers(users);
        return result;
    }

    @PostMapping("/startTimeScheduled")
    public String startTimeScheduled(){
        //scheduledTaskControl.scheduleTaskAtFixedRate( (param1, param2) -> {
        //    //log.info(param1+param2);
        //},"TimerTask1");
        return "定时任务开启成功";
    }

    @PostMapping("/createOrder")
    public String createOrder(@RequestBody Order order){
        order.setOrderStatus("未支付");
        Date curDateTime=new Date();
        order.setCreateTime(curDateTime);
        Integer insertResult = orderMapper.insertOrder(order);
        //scheduledTaskControl.scheduleDelayedTask(curDateTime, (param1) -> {
        //    //log.info(param1+param2);
        //    orderMapper.updateOrderById(order.getOrderId());
        //    orderMapper.findOrderById(order.getOrderId());
        //},"delayTask1");
        return "成功插入"+insertResult+"条数据";
    }

    @GetMapping("/updateOrder")
    public String updateOrder(@RequestParam long orderId){
      long updateResult =  orderMapper.updateOrderById(orderId);



        return "已更新"+updateResult+"记录";
    }


    //创建新的sheet excel表格页填充数据
    @PostMapping("/exportExcel")
    public String exportExcel() throws IOException {
        ExcelUtil.setExportWorkbook("");
        Sheet exportSheet = ExcelUtil.getExportSheet();
        final List<List<String>> tableData = new ArrayList<List<String>>();
        // 造点数据
        tableData.add(Arrays.asList("男,一班,张三,60,61,2023-08-19,100001".split(",")));
        tableData.add(Arrays.asList("女,一班,胡八,20,20,2023-08-19,100006".split(",")));
        tableData.add(Arrays.asList("女,二班,陈十,40,41,2023-08-19,100008".split(",")));
        tableData.add(Arrays.asList("男,一班,李四,70,71,2023-08-19,100002".split(",")));
        tableData.add(Arrays.asList("女,二班,老九,30,31,2023-08-19,100007".split(",")));
        tableData.add(Arrays.asList("男,二班,王五,80,80,2023-08-19,100003".split(",")));
        tableData.add(Arrays.asList("男,二班,赵六,90,91,2023-08-19,100004".split(",")));
        tableData.add(Arrays.asList("女,一班,邹七,10,11,2023-08-19,100005".split(",")));
        tableData.add(Arrays.asList("女,二班,拾一,51,51,2023-08-19,100009".split(",")));
            // 设置表头样式
            final CellStyle headerCellStyle = ExcelUtil.createHeadStyle();
            // 填充表头数据
            final List<List<String>> headerData = new ArrayList<List<String>>();
            // 制造点表头的数据
            headerData.add(Arrays.asList("性别,班级,姓名,科目,科目,考试时间,考生号".split(",")));
            headerData.add(Arrays.asList("性别,班级,姓名,数学,语文,考试时间,考生号".split(",")));
            for (int i = 0; i < headerData.size(); i++) {
                // 创建表头行
                final Row headerRow = exportSheet.createRow(i);
                for (int j = 0; j < headerData.get(i).size(); j++) {
                    Cell cell = headerRow.createCell(j);
                    cell.setCellValue(headerData.get(i).get(j).toString());
                    //cell.setCellStyle(headerCellStyle);
                    exportSheet.setColumnWidth(j, 5000); //设置列宽度
                }
            }

            //表头垂直合并
            exportSheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
            exportSheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
            exportSheet.addMergedRegion(new CellRangeAddress(0, 1, 2, 2));
            exportSheet.addMergedRegion(new CellRangeAddress(0, 1, 5, 5));
            exportSheet.addMergedRegion(new CellRangeAddress(0, 1, 6, 6));
            //表头水平合并
            exportSheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 4));

       String exportExcelPath = ExcelUtil.dataToExcelUnitTable(tableData,headerData);
       return exportExcelPath;
    }


    //使用指定模板的sheet excel表格页填充数据
    @GetMapping("/exportTemplateExcel")
    public String exportTemplateExcel() throws IOException {
        ExcelUtil.setExportWorkbook("D:\\新建文件夹 (2)\\test.xlsx");
        Sheet exportSheet = ExcelUtil.getExportSheet();
        final List<List<String>> tableData = new ArrayList<List<String>>();
        // 造点数据
        tableData.add(Arrays.asList("男,一班,张三,60,61,2023-08-19,100001".split(",")));
        tableData.add(Arrays.asList("女,一班,胡八,20,20,2023-08-19,100006".split(",")));
        tableData.add(Arrays.asList("女,二班,陈十,40,41,2023-08-19,100008".split(",")));
        tableData.add(Arrays.asList("男,一班,李四,70,71,2023-08-19,100002".split(",")));
        tableData.add(Arrays.asList("女,二班,老九,30,31,2023-08-19,100007".split(",")));
        tableData.add(Arrays.asList("男,二班,王五,80,80,2023-08-19,100003".split(",")));
        tableData.add(Arrays.asList("男,二班,赵六,90,91,2023-08-19,100004".split(",")));
        tableData.add(Arrays.asList("女,一班,邹七,10,11,2023-08-19,100005".split(",")));
        tableData.add(Arrays.asList("女,二班,拾一,51,51,2023-08-19,100009".split(",")));
        // 设置表头样式
        final CellStyle headerCellStyle = ExcelUtil.createHeadStyle();
        // 填充表头数据
        final List<List<String>> headerData = new ArrayList<List<String>>();
        headerData.add(Arrays.asList("".split(",")));
        headerData.add(Arrays.asList("".split(",")));

        String exportExcelPath = ExcelUtil.dataToExcelUnitTable(tableData,headerData);
        return exportExcelPath;
    }



    @GetMapping("/getUserInfo")
    public User getUserInfo(@RequestParam String  userId){
         User user = userMapper.getUserByUserId(userId);
        return user;
    }

    @PostMapping("/uploadFile")
    public Object uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传的文件不能为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 检查文件扩展名是否为 .xlsx
        if (!fileName.endsWith(".xlsx")) {
            return "上传的文件必须是 .xlsx 格式";
        }

        // 如果需要，可以进一步处理文件，例如保存到服务器
        try {
            // 保存文件到指定路径
            String uploadPath = "D://upload//";
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            File dest = new File(uploadPath + fileName);
            file.transferTo(dest);
            List<List<Object>> excelDataList=new ArrayList<List<Object>>();
            excelDataList=ExcelUtil.readImportExcel(dest);
            return excelDataList;
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }



    //服务端启用sse模式发送流式数据 客户端前端使用请求方法返回的response对象，response.body.getReader()拿到reader对象不断去获取流数据
    @RequestMapping("/testSse")
    public SseEmitter testSse(@RequestBody String inputParameter, HttpServletResponse response) {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        SseEmitter emitter = new SseEmitter();

        // Simulate asynchronous data retrieval from the database
        new Thread(() -> {
            try {
                // Query the database based on the input parameter and send data in batches
                for (int i = 0; i < 10; i++) {
                    String data = "Data batch " + i + " for parameter: ";
                    emitter.send(data);
                    Thread.sleep(1000); // Simulate delay between batches
                }

                emitter.complete(); // Complete the SSE connection
            } catch (Exception e) {
                emitter.completeWithError(e); // Handle errors
            }
        }).start();

        return emitter;
    }

}
